// app.js
App({
    globalData: {
        userInfo: null,
        userType: '',
    isLoggedIn: false,
    isAdmin: false, // 默认不是主理人
    userBalance: 0, // 用户余额
        adminPassword: '123456' ,// 默认密码
    },
     // 登录方法
  login: function(role, password) {
    console.log('登录请求:', role, password);
    
    if (role === 'admin') {
      if (password === this.globalData.adminPassword) {
        this.globalData.isAdmin = true;
        wx.setStorageSync('userRole', 'admin');
        console.log('主理人登录成功');
        return true;
      } else {
        console.log('主理人密码错误');
        return false;
      }
    } else if (role === 'user') {
      this.globalData.isAdmin = false;
      wx.setStorageSync('userRole', 'user');
      
      // 加载用户余额
      const balance = wx.getStorageSync('userBalance') || 0;
      this.globalData.userBalance = balance;
      
      return true;
    }
    return false;
  },
  // 设置用户余额
  setUserBalance: function(balance) {
    this.globalData.userBalance = balance;
    wx.setStorageSync('userBalance', balance);
  },
  
  // 获取用户角色
  getUserRole: function() {
    return wx.getStorageSync('userRole') || 'user';
  },
    onLaunch: function() {
        // 从存储中获取主理人密码
        const adminPassword = wx.getStorageSync('adminPassword') || '123456';
        this.globalData.adminPassword = adminPassword;
        // 初始化时获取用户角色
    const role = this.getUserRole();
    this.globalData.isAdmin = role === 'admin';
    this.restoreLoginState();
    if (role === 'user') {
      // 加载用户余额
      const balance = wx.getStorageSync('userBalance') || 0;
      this.globalData.userBalance = balance;
    }
    },
    // 恢复登录状态
  restoreLoginState: function() {
    try {
      const userInfo = wx.getStorageSync('userInfo');
      const userType = wx.getStorageSync('userType');
      const isLoggedIn = wx.getStorageSync('isLoggedIn');
      const isAdmin = wx.getStorageSync('isAdmin');
      
      if (userInfo && isLoggedIn) {
        this.globalData.userInfo = userInfo;
        this.globalData.userType = userType;
        this.globalData.isLoggedIn = true;
        this.globalData.isAdmin = isAdmin;
      }
    } catch (e) {
      console.error('恢复登录状态失败:', e);
    }
  },
  onLaunch() {
    // 展示本地存储能力
    const logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)

    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
      }
    })
  },
  globalData: {
    userInfo: null
  }
})
